<!-- 列车实时轨迹功能 -->
<template>
  <div class="center-wrapper">
    <!-- 地铁线路 -->
    <div id="subLine-controller">
      <div class="title-bg">
        <i class="iconfont metro-lineRoute"></i> 地铁线路
      </div>
      <div class="item-wrapper">
        <div
          class="item"
          v-for="(item, index) in subLineData"
          :key="index"
          @click.stop="handleItemClick(item)"
        >
          <div
            class="box"
            :style="{
              borderColor: item.color,
              backgroundColor: item.choosed ? item.color : 'rgba(0,0,0,0)',
            }"
          ></div>
          <span :style="{ color: '#34c5cf' }">{{ item.name.slice(-3) }}</span>
        </div>
      </div>
    </div>
    <!-- 站点列表 -->
    <div id="station-controller">
      <div class="title-bg"><i class="iconfont metro-ditie"></i> 地铁站点</div>
      <div class="item-wrapper">
        <div class="item" :key="index" v-for="(item, index) in stationData">
          <div
            class="box"
            :style="{
              backgroundColor:
                index - 1 < metroIndex ? '#fff' : 'rgba(0,0,0,0)',
            }"
          ></div>
          <span :style="{ color: '#34c5cf' }">{{ item.name }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import * as Cesium from 'cesium'
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { useLineData } from '@/store'
import SimpleLabel from '@/cesiumTools/Bubble/htmlMarker'
import { getPositions, getSiteTimes } from '@/cesiumTools/core'
const lineData = useLineData()
const subLineData = ref([])
const stationData = ref([])
const currentLine = ref({})
const metroIndex = ref(0)
let viewer
let trainEntity
let popupController

onMounted(() => {
    subLineData.value = lineData.allData.map(item => ({ ...item, choosed: false }))
    viewer = lineData.Viewer
})

onBeforeUnmount(()=>{
    // 清除所有副作用
    removeCurrentRoute()
})

// 假设从服务端获取到列车的实时信息
const getTrainDataByLineId = (id) => {
    return new Promise((resolve, reject) => {
        // 构造一个随机的站点index
        let startIndex = 0
        const startStationInfo = stationData.value[startIndex]
        const endStationInfo = stationData.value[startIndex + 1]
        // 由于站点坐标和路径坐标可能不会完全匹配，这里只是模拟数据，给列车虚构一个坐标点
        const trainData = {
            startIndex,
            currentPassengers: Math.ceil(Math.random() * 1000),
            startStation: startStationInfo,
            destination: endStationInfo,
            lineName: currentLine.value.name,
            currentSpeed: Math.ceil(Math.random() * 100),
            currentPosition: currentLine.value.paths[2],
        }
        resolve(trainData)
    })
}

const handleItemClick = async (item) => {
    // 如果点击的是同一个站线，返回
    if (currentLine.value?.name == item.name) return
    removeCurrentRoute()
    currentLine.value = item
    // 点击站线，更新数据，渲染轨道列车，视角跳转，渲染popup
    const { stationsList, id } = item;
    // 控制ui
    subLineData.value.forEach(item => {
        if (item.id == id) {
            item.choosed = true;
        } else {
            item.choosed = false
        }
    })
    stationData.value = stationsList;
    // 从模拟服务端获取列车信息
    const trainInfo = await getTrainDataByLineId(id)
    // 渲染轨道列车
    renderTrain(trainInfo)
    // 渲染气泡框
    renderBubble(trainInfo)
}

// 渲染气泡框
const renderBubble = (trainInfo) => {
    const { currentPosition, currentPassengers, lineName } = trainInfo
    const position=new Cesium.Cartesian3.fromDegrees(currentPosition.lng,currentPosition.lat)
    popupController=new SimpleLabel(viewer,{
        position,
        label:null,
        isShow:true,
        color:'#fff',
        scaleByDistance:null,
        offset:[130,205],
        attr:{
          currentPassengers,
          lineName
        },
        type:'carPopup'
    })
    popupController.addLabel()
}

// 渲染轨道列车
const renderTrain = (trainInfo) => {
    // 获取出发站点，得到metroIndex
    const { startIndex,currentPosition, currentSpeed } = trainInfo
    metroIndex.value=startIndex
    const pathIndex= currentLine.value.paths.findIndex(path => path===currentPosition)
    const { property, startTime, endTime } = handlePosition(currentSpeed,pathIndex)
    trainEntity = viewer.entities.add({
        availability: new Cesium.TimeIntervalCollection([
            new Cesium.TimeInterval({
                start: startTime,
                stop: endTime,
            }),
        ]),
        position: property,
        orientation: new Cesium.VelocityOrientationProperty(property),
        model: {
            scale: 0.17,
            uri: "/src/assets/model/metro.gltf",
            minimumPixelSize: 40,
        }
    })

    viewer.trackedEntity = trainEntity;
    viewer.clock.startTime = startTime.clone();
    viewer.clock.stopTime = endTime.clone();
    viewer.clock.currentTime = startTime.clone();
    // 监听时钟，如果列车到达站点，更新列车人数信息，并给一个暂停时间
    viewer.clock.onTick.addEventListener(tickEventHandler);
}

// 处理漫游效果，使用TimeIntervalCollection
const handlePosition = (speed,pathIndex) => {
    const property = new Cesium.SampledProperty(Cesium.Cartesian3);
    let startTime = Cesium.JulianDate.fromDate(new Date(2015, 1, 1, 8));
    //通过速度计算最终时间
    const restPath = currentLine.value.paths.slice(pathIndex, currentLine.value.paths.length - 1)
    //转为Caterian3数组
    const positions = getPositions(restPath)
    //根据速度计算总时间和每段时间
    const { siteTimes, timeSum } = getSiteTimes(positions, speed)
    const endTime = Cesium.JulianDate.addSeconds(
        startTime,
        timeSum,
        new Cesium.JulianDate()
    );
    positions.forEach((position, index) => {
        const time = Cesium.JulianDate.addSeconds(startTime, siteTimes[index], new Cesium.JulianDate())
        property.addSample(time, position);
    })
    return {
        property,
        startTime,
        endTime
    }
}

// 当距离小于20米的时候，就可以给列车一个暂停
let apporachDistance=20
const tickEventHandler=()=>{
    const startPosition = trainEntity.position.getValue(viewer.clock.currentTime);
    //通过当前的metroIndex和速度计算下一个站点的坐标
    const {position}=stationData.value[metroIndex.value + 1]
    const endPosition=new Cesium.Cartesian3.fromDegrees(position.lng,position.lat)
    let distance = Cesium.Cartesian3.distance(startPosition, endPosition);
    if(distance<=apporachDistance){
        // 站点id变大，下一次计算的distance也会变大
        metroIndex.value++
        // 将列车暂停
        viewer.clock.shouldAnimate = false;
        // 2s后恢复
        setTimeout(() => {
           viewer.clock.shouldAnimate = true;
        }, 2000);
    }
    // 还需要通过startPosition计算气泡框坐标
    popupController && popupController.changePosition(startPosition)
}

const removeCurrentRoute=()=>{
    viewer.trackedEntity=null
    trainEntity && viewer.entities.remove(trainEntity)
    popupController && popupController.removeMarker()
    tickEventHandler && viewer.clock.onTick.removeEventListener(tickEventHandler);
}
</script>

<style scoped>
.wrapper {
  width: 100%;
  height: 100%;
}

/* 地铁线路列表 */
#subLine-controller {
  position: absolute;
  bottom: 5%;
  left: 32.5%;
  transform: translateX(-50%);
  width: 180px;
  height: 200px;
  background-color: rgba(0, 0, 0, 0.3);
  border: 1px solid #ab7818;
  display: flex;
  flex-direction: column;
}

.box {
  width: 10px;
  height: 10px;
  border-width: 1px;
  border-style: solid;
  background: transparent;
  user-select: all;
  cursor: pointer;
  transition: all 0.3s linear;
}

.item {
  width: 64.992px;
  height: 20.006px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 0.156vw;
  background-color: rgba(255, 255, 255, 0.2);
  border: 1px solid #885f12;
  color: #fff;
  font-size: 0.521vw;
  pointer-events: all;
}

.item:hover {
  border: 1px solid #d8961a;
}

.item > span {
  line-height: 0.469vw;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 2.083vw;
}

.item > input {
  outline: none;
  border: none;
  transition: all 0.3s ease;
}

.item-wrapper {
  display: flex;
  justify-content: space-around;
  align-content: space-around;
  flex-wrap: wrap;
  flex: 1;
  padding: 4px;
  overflow: hidden;
}

/* 站点列表 */
#station-controller {
  width: 600px;
  height: 200px;
  border: 1px solid #ab7818;
  background-color: rgba(0, 0, 0, 0.3);
  position: absolute;
  left: 38%;
  bottom: 5%;
  color: #fff;
  display: flex;
  flex-direction: column;
}

#station-controller .item-wrapper {
  justify-content: flex-start;
}

#station-controller .item {
  margin: 0 7px;
}

.title-bg {
  width: 100%;
  height: 30px;
  background: url('/src/assets/uiResources/title-bg.png');
  background-size: contain;
  color: #fff;
  background-repeat: no-repeat;
  line-height: 30px;
  margin-left: 10px;
  background: rgb(255, 255, 255);
  background-image: linear-gradient(
    180deg,
    rgba(255, 255, 255, 1) 9%,
    rgba(211, 156, 50, 1) 57%
  );
  background-clip: text;
  -webkit-text-fill-color: transparent;
}

/* 站控措施图例 */
.right-wrapper {
  width: 11.417vw;
  height: 100%;
  position: absolute;
  right: 0px;
  top: 2.083vw;
}

.right-wrapper .query-item-title {
  cursor: default;
  pointer-events: none;
}

.right-wrapper .query-item-title::after {
  width: 20px;
  left: -20px;
}

.legend .query-item i {
  pointer-events: none;
  cursor: default;
}

.title {
  color: #fff;
}
</style>
